import pandas as pd
import argparse
from datetime import datetime
from jinja2 import Template
import os

def read_ai_news_from_excel(file_path, sheet_name=0):
    """从Excel文件中读取AI新闻数据"""
    try:
        df = pd.read_excel(file_path, sheet_name=sheet_name)
        # 处理可能的列名不一致问题
        df.columns = df.columns.str.lower().str.strip()
        
        # 确保列名正确
        column_mapping = {}
        for col in df.columns:
            if 'title' in col or '标题' in col:
                column_mapping[col] = 'title'
            elif 'content' in col or '内容' in col:
                column_mapping[col] = 'content'
            elif 'source' in col or '来源' in col:
                column_mapping[col] = 'source'
        
        df = df.rename(columns=column_mapping)
        
        # 转换为字典列表
        news_data = []
        for _, row in df.iterrows():
            if pd.notna(row.get('title')) and pd.notna(row.get('content')):
                news_data.append({
                    'title': row.get('title', ''),
                    'content': row.get('content', ''),
                    'source': row.get('source', '未知来源')
                })
        
        return news_data
    except Exception as e:
        print(f"读取Excel文件时出错: {e}")
        return []

def generate_html(news_data, output_path="ai_daily_report.html"):
    """生成HTML页面"""
    # 获取当前日期
    today = datetime.now()
    date_str = f"{today.year}年{today.month}月{today.day}日"
    
    # HTML模板
    html_template = """
<!DOCTYPE html>
<html lang="zh-CN">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>AI觉醒日报</title>
  <style>
    body {
      font-family: 'Microsoft YaHei', sans-serif;
      background: linear-gradient(135deg, #0f2027, #203a43, #2c5364);
      margin: 0;
      padding: 0;
      color: #fff;
    }

    .container {
      max-width: 600px;
      margin: 30px auto;
      background: rgba(255, 255, 255, 0.05);
      padding: 25px;
      border-radius: 20px;
      box-shadow: 0 12px 35px rgba(0, 0, 0, 0.5);
      backdrop-filter: blur(10px);
      border: 1px solid rgba(0, 255, 204, 0.2);
    }

    .header {
      text-align: center;
      font-size: 32px;
      font-weight: bold;
      color: #00ffcc;
      letter-spacing: 2px;
      margin-bottom: 5px;
    }

    .date-tag {
      text-align: center;
      font-size: 16px;
      color: #ffde59;
      margin-bottom: 20px;
      font-weight: bold;
    }

    .sub-header {
      text-align: center;
      font-size: 18px;
      color: #00e6ff;
      margin-bottom: 25px;
      font-weight: 500;
    }

    .news-card {
      background: rgba(0, 255, 204, 0.08);
      border: 1px solid rgba(0, 255, 204, 0.25);
      border-radius: 12px;
      padding: 15px 20px;
      margin: 18px 0;
      transition: all 0.3s ease;
    }

    .news-card:hover {
      background: rgba(0, 255, 204, 0.15);
      transform: translateY(-4px);
      box-shadow: 0 6px 20px rgba(0, 255, 204, 0.3);
    }

    .news-title {
      font-size: 17px;
      font-weight: bold;
      color: #00ffcc;
      margin-bottom: 8px;
    }

    .news-content {
      font-size: 15px;
      line-height: 1.7;
      color: #e6f7f7;
      margin-bottom: 10px;
    }

    .news-source {
      font-size: 13px;
      color: #aaa;
      text-align: right;
    }

    .footer {
      text-align: center;
      margin-top: 30px;
      font-size: 14px;
      background: rgba(0, 255, 204, 0.1);
      padding: 12px;
      border-radius: 10px;
      color: #fff;
      font-weight: bold;
      border: 1px solid rgba(0, 255, 204, 0.3);
    }
  </style>
  <script>
    window.onload = function () {
      const today = new Date();
      const year = today.getFullYear();
      const month = today.getMonth() + 1;
      const day = today.getDate();
      document.getElementById("date-tag").innerText = `${year}年${month}月${day}日`;
    }
  </script>
</head>

<body>
  <div class="container">
    <div class="header">最新AI日报</div>
    <div class="date-tag" id="date-tag">{{ date_str }}</div>
    <div class="sub-header">今日AI领域重要动态</div>

    {% for news in news_data %}
    <div class="news-card">
      <div class="news-title">{{ loop.index }}. {{ news.title }}</div>
      <div class="news-content">{{ news.content }}</div>
      <div class="news-source">来源：{{ news.source }}</div>
    </div>
    {% endfor %}

    <div class="footer">每日为您提供最新AI资讯 ｜ 李明洲制作</div>
  </div>
</body>

</html>
"""
    
    # 使用Jinja2模板渲染
    template = Template(html_template)
    html_content = template.render(news_data=news_data, date_str=date_str)
    
    # 写入文件
    with open(output_path, 'w', encoding='utf-8') as f:
        f.write(html_content)
    
    print(f"AI日报已生成: {output_path}")
    return output_path

def main():
    """主函数"""
    parser = argparse.ArgumentParser(description='AI日报生成器')
    parser.add_argument('--excel', '-e', required=True, help='Excel文件路径')
    parser.add_argument('--output', '-o', default='ai_daily_report.html', help='输出HTML文件路径')
    parser.add_argument('--sheet', '-s', default=0, help='Excel工作表名称或索引')
    
    args = parser.parse_args()
    
    # 读取Excel数据
    news_data = read_ai_news_from_excel(args.excel, args.sheet)
    
    if not news_data:
        print("未找到有效的新闻数据")
        return
    
    # 生成HTML
    generate_html(news_data, args.output)

if __name__ == "__main__":
    main()